<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button :loading="downloadLoading" class="filter-item" type="default" @click="handleDownload">
        导出excel
      </el-button>
      <el-divider direction="vertical" />
      <el-button class="filter-item" type="primary" @click="handleCreate">
        {{ textMap.create }}
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      :row-class-name="tableRowClassName"
      element-loading-text="Loading"
      border
      fit
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="描述">
              <span>{{ props.row.description }}</span>
            </el-form-item>
            <el-form-item label="访问量">
              <span>{{ props.row.visits }}</span>
            </el-form-item>
            <el-form-item :label="otherPathLabel[props.row.type]">
              <span>{{ props.row.otherPath }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ props.row.createTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间">
              <span>{{ props.row.updateTime }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column sortable label="排序" prop="order" align="center" width="100px" />
      <el-table-column label="广告类型" align="center" min-width="120px">
        <template #default="{row}">
          <span>{{ row.type | typeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告标题" prop="title" align="center" min-width="120px" />
      <el-table-column label="广告图片" min-width="180px" align="center">
        <template #default="{row}">
          <el-image :src="row.srcPath" style="width: 135px; height: 135px;">
            <template #placeholder class="image-slot">
              加载中<span class="dot">...</span>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="判定归属" align="center" min-width="140px">
        <template #default="{row}">
          <span>{{ row.belong | belongFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" min-width="140px">
        <template #default="{row}">
          <el-tag
            :type="row.valid !== 1 ? 'danger' : 'success'"
            effect="dark"
          >
            {{ row.valid | validFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNumber" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :width="'700px'">
      <el-form ref="dataForm" :rules="rules" :model="advertisement" label-position="left" label-width="200px" class="data-form">
        <el-form-item label="排序" prop="order">
          <el-input v-model="advertisement.order" clearable placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="advertisement.type" clearable placeholder="请选择广告类型" class="data-form-select">
            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item" :value="index" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="advertisement.type === 0 || advertisement.type" :prop="advertisement.type === 2 || advertisement.type === 3 ? 'otherPath' : ''" :label="otherPathLabel[advertisement.type]">
          <el-input v-model="advertisement.otherPath" clearable placeholder="请输入数据" />
        </el-form-item>
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="advertisement.title" clearable placeholder="请输入广告标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="advertisement.description" clearable placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="判定归属" prop="belong">
          <el-select v-model="advertisement.belong" clearable placeholder="请选择判定归属" class="data-form-select">
            <el-option v-for="(item, index) in shopList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="valid">
          <el-select v-model="advertisement.valid" clearable placeholder="请选择是否启用" class="data-form-select">
            <el-option v-for="(item, index) in validOptions" :key="index" :label="item" :value="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" :prop="dialogStatus==='create'?'file':''">
          <el-upload
            ref="image"
            drag
            action="#"
            accept="image/*"
            :on-change="changeFile"
            :show-file-list="false"
            :auto-upload="false"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>

        </el-form-item>
        <el-form-item v-if="imageUrl" label="已选图片">
          <el-image :src="imageUrl" :preview-src-list="[imageUrl]">
            <template #placeholder>
              加载中<span class="dot">...</span>
            </template>
          </el-image>
        </el-form-item>
      </el-form>

      <template #footer class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import Ad from '@/api/ad.js'
  import shop from '@/api/shop.js'
  import Pagination from '@/components/Pagination'
  import { exportExcel } from '@/utils'

  // 自定义数据
  const validMap = ['否', '是']
  const typeMap = ['图片', '进入店铺', '广告页面', '拨打电话']
  const otherPathMap = ['图片资源', '资源路径', '广告链接', '电话号码']
  let that

  export default {
    name: 'AdList',
    components: { Pagination },
    // 过滤表格数据
    filters: {
      belongFilter(belong) {
        const data = that.shopList.filter(function(item) {
          return item.id === belong
        })
        return data[0] && data[0].name
      },
      validFilter(valid) {
        return validMap[valid]
      },
      typeFilter(type) {
        return typeMap[type]
      }
    },
    data() {
      return {
        // 商家
        shopList: [{ name: '初始化', id: 99999 }],
        shopQuery: {
          pageNumber: 1,
          pageSize: 9999
        },
        // 列表
        list: null,
        total: 0,
        listQuery: {
          pageNumber: 1,
          pageSize: 20
        },
        // 选项
        validOptions: validMap,
        typeOptions: typeMap,
        otherPathLabel: otherPathMap,
        listLoading: true,
        // dialog 框
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改广告信息',
          create: '新增广告'
        },
        advertisement: {
          type: undefined,
          otherPath: '',
          title: '',
          description: '',
          belong: '',
          valid: '',
          order: '',
          file: ''
        },
        fileRules: undefined,
        rules: {
          otherPath: [{ required: true, message: '请输入数据', trigger: 'change' }],
          type: [{ required: true, message: '请输入广告类型', trigger: 'change' }],
          order: [{ required: true, message: '请输入排序', trigger: 'change' }],
          title: [{ required: true, message: '请输入广告标题', trigger: 'change' }],
          description: [{ required: true, message: '请输入内容简介', trigger: 'change' }],
          belong: [{ required: true, message: '请选择判定归属', trigger: 'change' }],
          valid: [{ required: true, message: '请选择是否启用', trigger: 'change' }],
          file: [{ required: true, message: '请选择上传图片文件', trigger: 'change' }]
        },
        // 图片url
        imageUrl: '',
        downloadLoading: false
      }
    },
    beforeCreate: function() {
      that = this
    },
    async created() {
      await this.getList()
      await this.getShop()
    },
    methods: {
      /**
       * @description 表格切换颜色
       */
      tableRowClassName({ rowIndex }) {
        if (rowIndex % 2 !== 0) {
          return 'different-row'
        }
      },
      /**
       * @description 更改图片
       */
      changeFile({ status, raw: file }) {
        if (file.size / 1024 / 1024 > 1) {
          this.$message({
            message: '您上传的图片大小超过1M,请压缩后上传',
            type: 'warning'
          })
          return
        }
        if (status === 'ready') {
          this.imageUrl = URL.createObjectURL(file)
          this.advertisement.file = file
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate('file')
        })
      },
      /**
       * @desc 获取商家
       */
      async getShop() {
        this.listLoading = true
        const { data } = await shop.getShop(this.shopQuery)
        data.unshift({ id: 0, name: '总台' })
        this.shopList = data
        this.listLoading = false
      },
      /**
       * @desc 获取列表
       */
      async getList() {
        this.listLoading = true
        const { data, total } = await Ad.getAd(this.listQuery)
        data.map(value => {
          value.srcPath = 'http://qn.schoolbangbang.com/' + value.srcPath
        })
        this.list = data
        this.total = total
        this.listLoading = false
      },
      /**
       * @desc 开启创建窗口
       */
      handleCreate() {
        this.advertisement = {
          type: null,
          otherPath: '',
          order: '',
          title: '',
          description: '',
          belong: '',
          valid: '',
          file: ''
        }
        this.imageUrl = ''
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * @desc 点击保存 - 创建
       */
      createData() {
        this.$refs['dataForm'].validate(async valid => {
          if (!valid) return
          await Ad.insertAd(this.advertisement)
          await this.getList()
          this.dialogFormVisible = false
          this.$message({
            message: '新增成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      /**
       * @desc 开启更新窗口
       */
      handleUpdate(row) {
        delete row.visits
        this.advertisement = Object.assign({}, row) // copy obj
        this.imageUrl = this.advertisement.srcPath
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          if (this.$refs['image']) {
            this.$refs['image'].value = ''
          }
        })
      },
      /**
       * @desc 点击保存 - 更新
       */
      updateData() {
        this.$refs['dataForm'].validate(async valid => {
          if (!valid) return
          const adData = Object.assign({}, this.advertisement)
          adData.srcPath = adData.srcPath.replace('http://qn.schoolbangbang.com/', '')
          await Ad.updateAd(adData.id, adData)
          await this.getList()
          this.dialogFormVisible = false
          this.$message({
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      /**
       * @desc 点击删除
       */
      handleDelete({ id, title }) {
        this.$confirm(`是否确定删除广告:${title}`, '删除警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await Ad.deleteAd(id)
          await this.getList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
          .catch(err => {
            err === 'cancel' && this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      /**
       * @description 导出Excel
       */
      async handleDownload() {
        this.downloadLoading = true
        const header = ['排序', '广告类型', '广告标题', '描述', '判定归属', '是否启用', '访问量', '创建时间', '更新时间']
        const filterVal = ['order', 'type', 'title', 'description', 'belong', 'valid', 'visits', 'createTime', 'updateTime']
        const data = this.formatJson(filterVal, this.list)
        await exportExcel(header, data, '广告列表')
        this.downloadLoading = false
      },
      /**
       * @description 格式化
       */
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'belong') {
            return this.$options.filters['belongFilter'](v[j])
          } else if (j === 'valid') {
            return validMap[v[j]]
          } else if (j === 'type') {
            return typeMap[v[j]]
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>

<style lang="scss" scoped>
	/deep/ .el-table .different-row {
		background: #eef5fe;
		color: #be9117;
	}
	.data-form {
		/deep/ .el-form-item:first-child {
			.el-form-item__content {
				line-height: 0;
				position: relative;
				font-size: 14px;
			}
		}
	}
	/deep/ .demo-table-expand {
		font-size: 0;
	}
	/deep/ .demo-table-expand label {
		width: 90px;
		color: #99a9bf;
	}
	/deep/ .demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}
</style>
